import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart';
import 'package:hayll_app_village_master/hayll/village_manager/home/village_access_robbit_component/bean/village_access_robbit.dart';
import 'package:intl/intl.dart';
import 'package:sprintf/sprintf.dart';

import 'action.dart';
import 'state.dart';

var _f = DateFormat('yyyy/MM/dd hh:mm:ss');

String _convertDate(int datestmp) {
  return _f.format(DateTime.fromMillisecondsSinceEpoch(datestmp));
}

Widget buildView(VillageAccessRobbitState state, Dispatch dispatch,
    ViewService viewService) {
  return Scaffold(
    body: ListView.builder(
      itemCount: state.robbitList.length,
      itemBuilder: (context, position) {
        return _createRobbitMainUI(
            state, dispatch, viewService, state.robbitList[position]);
      },
    ),
    floatingActionButton: FloatingActionButton(
      child: Icon(Icons.add),
      onPressed: () {
        dispatch(VillageAccessRobbitActionCreator.registerDevice());
      },
    ),
  );
}

Widget _createRobbitMainUI(VillageAccessRobbitState state, Dispatch dispatch,
    ViewService viewService, VillageAccessRobbitSimpleResult robbit) {
  var card = Card(
      clipBehavior: Clip.antiAlias,
      margin: EdgeInsets.all(8),
      elevation: 8,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(8))),
      child: Stack(
        alignment: AlignmentDirectional.topEnd,
        children: <Widget>[
          _createRobbitMainInfoUI(state, dispatch, viewService, robbit),
          IconButton(
            icon: Icon(
              state.editingDeviceId == robbit.switchId
                  ? Icons.arrow_drop_down
                  : Icons.arrow_right,
              color: Colors.blueAccent,
            ),
            onPressed: () {
              dispatch(VillageAccessRobbitActionCreator.openSettingPage(
                  robbit.switchId));
            },
          ),
        ],
      ));

  return card;
}

Widget _createRobbitMainInfoUI(
    VillageAccessRobbitState state,
    Dispatch dispatch,
    ViewService viewService,
    VillageAccessRobbitSimpleResult robbit) {
  var childs = List<Widget>();
  childs.add(_createRobbitMainBaseInfoUI(state, dispatch, viewService, robbit));
  if (robbit.switchId == state.editingDeviceId) {
    childs.add(Divider(
      height: 2,
    ));
    childs.add(_createRobbitSettingUI(state, dispatch, viewService, robbit));
  }
  return Container(
    child: Column(
      children: childs,
    ),
  );
}

Widget _createRobbitMainBaseInfoUI(
    VillageAccessRobbitState state,
    Dispatch dispatch,
    ViewService viewService,
    VillageAccessRobbitSimpleResult robbit) {
  var isWorking = robbit.status == 1;
  return Row(
    children: <Widget>[
      Container(
        decoration: BoxDecoration(
          color: isWorking ? Colors.blue : Colors.grey,
        ),
        width: 48,
        height: 96,
        child: Center(
          widthFactor: 2,
          child: Text(
            isWorking ? '在\n线' : '离\n线',
            style: TextStyle(color: isWorking ? Colors.white70 : Colors.black),
          ),
        ),
      ),
      Container(
        padding: EdgeInsets.only(left: 8, top: 8, right: 8, bottom: 8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text(
                  robbit.switchName != null
                      ? robbit.switchName
                      : (robbit.location != null) ? robbit.location : '未命名',
                  style: TextStyle(fontSize: 16),
                ),
              ],
            ),
            Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text(
                  'mac:${robbit.termId}[${robbit.deviceTypeName}]',
                  style: TextStyle(fontSize: 12),
                )
              ],
            ),
            Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text(
                  '最近在线时间:${_convertDate(robbit.lastLoginTime)}',
                  style: TextStyle(fontSize: 10, fontStyle: FontStyle.italic),
                )
              ],
            ),
            Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text(
                  '版本: ${robbit.appVersion}',
                  style: TextStyle(fontSize: 10, fontStyle: FontStyle.italic),
                ),
                Text(
                  ' ${robbit.activeStatusDesc}',
                  style: TextStyle(
                      fontSize: 10,
                      fontStyle: FontStyle.italic,
                      color:
                          robbit.activeStatus ? Colors.grey : Colors.red[400]),
                ),
              ],
            ),
          ],
        ),
      ),
    ],
  );
}

Widget _createAppVersionViews(VillageAccessRobbitState state, Dispatch dispatch,
    ViewService viewService, VillageAccessRobbitSimpleResult robbit) {
  if (robbit.lastAppVersion == null) {
    return Container(
      padding: EdgeInsets.only(left: 8),
      child: Row(
        children: <Widget>[
          createTipsView('版本:${robbit.appVersion}'),
          createTipsView(' 无可升级版本'),
        ],
      ),
    );
  } else {
    return Container(
      padding: EdgeInsets.only(left: 8),
      child: Row(
        children: <Widget>[
          createTipsView('版本:${robbit.appVersion}'),
          createTipsView(' 可升级至:${robbit.lastAppVersion.version}'),
          Container(
            // padding: EdgeInsets.only(left: 8),
            height: 24,
            width: 24,
            child: IconButton(
              padding: EdgeInsets.all(0),
              icon: Icon(
                Icons.update,
                color: Colors.blueAccent,
              ),
              onPressed: () {
                dispatch(VillageAccessRobbitActionCreator.updateDeviceVersion(
                    robbit.termId, robbit.lastAppVersion.versionId));
              },
            ),
          ),
        ],
      ),
    );
  }
}

Widget createTipsView(String msg, {double fontSize = 12}) {
  return Text(
    msg,
    style: TextStyle(fontSize: fontSize),
  );
}

Widget _createRobbitSettingUI(VillageAccessRobbitState state, Dispatch dispatch,
    ViewService viewService, VillageAccessRobbitSimpleResult robbit) {
  var isWorking = robbit.status == 1;
  return Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      Row(
        children: <Widget>[
          Expanded(
            child: Padding(
              padding: EdgeInsets.all(8),
              child: _createSettingButton(
                  '开门日志',
                  Icon(
                    Icons.list,
                    color: Colors.blueAccent,
                  ), () {
                dispatch(VillageAccessRobbitActionCreator.scanDeviceLog(
                    robbit.switchId));
              }),
            ),
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(),
              child: _createSettingButton(
                  '重启设备',
                  Icon(
                    Icons.list,
                    color: Colors.blueAccent,
                  ), () {
                dispatch(VillageAccessRobbitActionCreator.rebootDevice(
                    robbit.termId));
              }),
            ),
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(left: 8, right: 8),
              child: _createSettingButton(
                  robbit.activeStatusDesc,
                  Icon(
                    isWorking ? Icons.phonelink : Icons.phonelink_erase,
                    color: Colors.blueAccent,
                  ), () {
                dispatch(VillageAccessRobbitActionCreator.activeDeviceVoip(
                    robbit.termId, robbit.switchId, !robbit.activeStatus));
              }),
            ),
          ),
        ],
      ),
      _createAppVersionViews(state, dispatch, viewService, robbit),
      Container(
        margin: EdgeInsets.only(left: 8, top: 8, right: 8),
        padding: EdgeInsets.all(8),
        decoration: ShapeDecoration(
          color: Colors.grey[100],
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(
              Radius.circular(4),
            ),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _createSeekBar(
              '人脸阈值',
              progress: robbit.recogniteLevel,
              onChanged: (val) {
                dispatch(VillageAccessRobbitActionCreator.changeDeviceValue(
                    robbit.termId, {
                  'faceScore': val,
                }));
              },
            ),
            _createSeekBar(
              '开锁时长',
              max: 10000,
              progress: robbit.unlocktime.toDouble(),
              onChanged: (val) {
                dispatch(VillageAccessRobbitActionCreator.changeDeviceValue(
                    robbit.termId, {
                  'unlockTime': val,
                }));
              },
            ),
            Center(
              child: FlatButton(
                splashColor: Colors.grey,
                textColor: Colors.blue,
                child: Text('保存设置'),
                onPressed: () {
                  dispatch(VillageAccessRobbitActionCreator.saveDeviceValue(
                      robbit.termId));
                },
              ),
            ),
          ],
        ),
      ),
      Container(
        width: 400,
        child: FlatButton(
          splashColor: Colors.grey,
          textColor: Colors.blue,
          child: Text(
            '删除设备',
            style: TextStyle(
              color: Colors.red[300],
            ),
          ),
          onPressed: () {
            dispatch(VillageAccessRobbitActionCreator.deleteDevice(
                robbit.switchId, robbit.termId));
          },
        ),
      ),
    ],
  );
}

Widget _createSeekBar(String title,
    {double min = 0,
    double max = 1,
    double progress = 0.5,
    ValueChanged<double> onChanged}) {
  return Container(
    height: 24,
    child: Row(
      children: <Widget>[
        createTipsView(title),
        Expanded(
          child: Slider(
            min: min,
            max: max,
            value: progress,
            activeColor: Colors.blueAccent,
            inactiveColor: Colors.grey,
            onChanged: onChanged,
          ),
        ),
        Text(
          sprintf('%.2f', [progress]),
          style: TextStyle(
            fontSize: 12,
            color: Colors.blue,
          ),
        ),
      ],
    ),
  );
}

Widget _createSettingButton(
    String title, Icon icon, void Function() onPressed) {
  return FlatButton(
    color: Colors.grey[100],
    textColor: Colors.blueAccent,
    child: Column(
      children: <Widget>[
        icon,
        createTipsView(title, fontSize: 10),
        createTipsView('') //占位
      ],
    ),
    onPressed: onPressed,
  );
}
